package com.qunduikj.sjb.sdk.crypt;


import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;

/**
 * 3DES加密工具类
 */
public class Des3Util {

    // 密钥
    private final static String secretKey = Constant.APPSECRET;
    // 向量
    private final static String iv = "01234567";
    // 加解密统一使用的编码方式
    private final static String encoding = "utf-8";

    private static Cipher cipher;

    static {
        try {
            Key deskey = null;
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);

            cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 3DES加密
     *
     * @param plainText 普通文本
     */
    public static String encode(String plainText) throws Exception {
        return Base64.encode(cipher.doFinal(plainText.getBytes(encoding)));
    }

    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     */
    public static String decode(String encryptText) throws Exception {
        return new String(cipher.doFinal(Base64.decode(encryptText)), encoding);
    }
}
